<?php
namespace WDB\Analyzer;
use WDB;

/**
 * WDB\Analyzer\Schema repository.
 *
 * @author Richard Ejem <richard(at)ejem.cz>
 */
class SchemaCache extends WDB\BaseObject
{
    /** @var \WDB\Database $c database connection for this analyzer */
    private $c;
    
    /** @var \WDB\Analyzer\Schema[] $schemata */
    private $schemata;
    
    
    public function __construct(WDB\Database $connection)
    {
        $this->c = $connection;
    }
    
    protected function dbident($schema)
    {
        return WDB\Utils\Strings::escapeWes($schema).'%'
               .WDB\Utils\Strings::escapeWes($this->c->connectionConfig->host).'%'
               .WDB\Utils\Strings::escapeWes($this->c->connectionConfig->user).'%'
               .substr(sha1('##'.$this->c->connectionConfig->password),0,6).'%'
               .$this->c->connectionConfig->port;
    }
    
    /**
     *
     * @param string $schema
     * @return Schema
     * 
     * @throws WDB\Exception\SchemaNotFound
     */
    public function getSchema($schema)
    {
        if (!isset($this->schemata[$schema]))
        {
            $schemaDir = WDB\Config::read('datadir').'schemata/';
            $file = $schemaDir.$this->dbident($schema).'.db';
            if (file_exists($file))
            {
                $this->schemata[$schema] = unserialize(file_get_contents($file));
            }
            else
            {
                $this->schemata[$schema] = new WDB\Analyzer\Schema($schema, $this->c);
                if (!is_dir($schemaDir))
                {
                    mkdir($schemaDir);
                }
                file_put_contents($file, serialize($this->schemata[$schema]), LOCK_EX);
            }
        }
        return $this->schemata[$schema];
    }
    
}
